const { courseModel, openedModel,workTeaModel, workPubModel } = require('../../model');
const { extensions } = require('../../config/dev.config');
const request = require('request');

module.exports = {
  scratchWorkUpload: async (req, res) => {
    const { org, id } = req.decode;
    const { scene = 'create', name, pageURL, fileURL, course = null, work = null } = req.query;
    const isCreate = scene === 'create';
    const isUpdate = scene === 'update';
    const isTeach = scene === 'teach';
    const model = isTeach ?  workTeaModel : workPubModel;

    const config = {
      name: name,
      pageURL: pageURL,
      fileURL: fileURL,
      updatedAt: Date.now()
    };
    const updateWhere = {
      id: work
    };
    isUpdate && Object.assign(updateWhere, {stu_id: id});
    isCreate && Object.assign(config, {stu_id: id, org: org, isOpened: 0, type: 'sb3', createdAt: Date.now()});
    console.log('mode:'+scene+',config:'+JSON.stringify(config));
    try {
      if (isTeach) {
        const createConfig =  {
          type: 'sb3',
          createdAt: Date.now()
        };
        const ori_work = await courseModel.findOne(['work_id'], {id: course});
        if (ori_work.work_id === parseInt(work)) {
          const work = await model.create(Object.assign(config, createConfig));
          await openedModel.update({work_id: work.dataValues.id, updatedAt: Date.now()},{stu_id: id, course_id: course});
        } else {
          await model.update(config,updateWhere)
        }
      }
      isUpdate && await model.update(config,updateWhere);
      isCreate && await model.create(config);
      return res.send({
        code: 20000
      })
    } catch (e) {
      console.log(e);
      return res.send({
        code: 10000
      })
    }
  },
  getTeachURL: async (req,res) => {
    const work_id = req.params.id;
    const { id } = req.decode;
    // TODO 可返回机构默认项目
    if(!work_id) return res.send({code: 10000, msg: "返回默认项目"});
    try {
      const openInfo = await openedModel.findOne(['stu_id'], { stu_id: id, work_id: work_id});
      if(!openInfo) return res.send({code: 10000, msg: "项目不存在"});
      const source = await workTeaModel.findOne(['fileURL','name'],{id: work_id});
      if(!source)  return res.send({code: 10000, msg: "未找到文件或没有权限"});
      return res.send({
        code: 20000,
        data: source
      });
    } catch (e) {console.log(e)}
  },
  getUpdateURL: async (req,res) => {
    const work_id = req.params.id;
    const { id } = req.decode;
    if(!work_id) return res.send({code: 10000, msg: "未提供文件id"});
    try {
      const source = await workPubModel.findOne(['fileURL','name'],{id: work_id, stu_id: id});
      if(!source)  return res.send({code: 10000, msg: "未找到文件或没有权限"});
      return res.send({
        code: 20000,
        data: source
      });
    } catch (e) {console.log(e)}
  },
  getCreateURL: async (req,res) => {
  },
  getWeather: function (req,res) {
    let url;
    const { weather } = req.params;
    const { location, day = 1 } = req.query;
    const part = 'https://free-api.heweather.net/s6/weather/';
    const type = {
      now: 'now?',
      forecast: 'forecast?'
    };
    if (weather && type.hasOwnProperty(weather))
      url = new URL(part + type[weather]);
    else
      url = new URL(part + type['now']);
    url.searchParams.append('location', location);
    url.searchParams.append('key', extensions.hfweather.API_KEY);
    request(url.href, function (error, response, body) {
      if (weather === 'forecast') return res.send(JSON.parse(body).HeWeather6[0].daily_forecast[day-1]);
      res.send(JSON.parse(body).HeWeather6[0].now);
    })
  },
  baiduToken: function (req,res) {
    const token_path = `https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=${extensions.speech2text.API_ID}&client_secret=${extensions.speech2text.API_KEY}`;
    console.log(token_path)
    request(token_path, function (error, response, body) {
      if (!error && response.statusCode === 200) {
        console.log(body)
        res.send(body);
      }
    })
  },
  baiduServer: function (req,res) {
    // console.log(req.body);
    request({
      url: 'http://vop.baidu.com/server_api',
      method: "POST",
      json: true,
      headers: {
        "content-type": "application/json",
      },
      body: req.body
    }, function(error, response, body) {
      if (!error && response.statusCode === 200) {
        console.log(body);
        res.send(body);
      }
    });
  }
};
